package com.steakliu.sun.client.netty.initializer;

import com.steakliu.sun.buffer.api.DataBuffer;
import com.steakliu.sun.client.api.ClientConfig;
import com.steakliu.sun.client.netty.handler.SunClientHandler;
import com.steakliu.sun.codec.SunDecoder;
import com.steakliu.sun.codec.SunEncoder;
import com.steakliu.sun.common.thread.ClientConcurrentThreadPool;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * 功能说明：
 * <p>
 * Original @Author: steakliu-刘牌, 2023-01-08  00:19
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class SunClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final ClientConfig config;

    private final ClientConcurrentThreadPool clientConcurrentThreadPool;

    private final DataBuffer requestBuffer;

    public SunClientChannelInitializer(ClientConfig config, ClientConcurrentThreadPool clientConcurrentThreadPool, DataBuffer requestBuffer) {
        this.config = config;
        this.clientConcurrentThreadPool = clientConcurrentThreadPool;
        this.requestBuffer = requestBuffer;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline()
                .addLast("encoder", new SunEncoder(config.isUseFlowControl(), config.getFlowControlType()))
                .addLast("decoder", new SunDecoder(config.isUseFlowControl(), config.getFlowControlType()))
                .addLast("clientIdleHandler", new IdleStateHandler(config.getHeartbeatInterval(), 0, 0, TimeUnit.MILLISECONDS))
                .addLast("clientHandler", new SunClientHandler(clientConcurrentThreadPool, config, requestBuffer));
    }
}
